<template>
  <div class="order-detail">
    <card :_Title="i18nText('common.details', '售后详情')" :_Size="16"></card>
    <!-- 操作按钮 -->
    <Card class="mb_10" v-if="(afterSale.serviceStatus == 'PASS' &&
          afterSale.serviceType != 'RETURN_MONEY') || (afterSale.afterSaleAllowOperationVO && afterSale.afterSaleAllowOperationVO.cancel)">
<!--      <Button type="success" @click="openModal"  size="small">
        {{ i18nText('afterSaleOrder.submitReturnLogisticsInformation', '提交物流') }}
      </Button>&nbsp;-->
      <Button type="success" @click="openModal" v-if="afterSale.serviceStatus == 'PASS' &&
          afterSale.serviceType != 'RETURN_MONEY'" size="small">
        {{ i18nText('afterSaleOrder.submitReturnLogisticsInformation', '提交物流') }}
      </Button>&nbsp;
      <Button type="error" @click="cancel(afterSale.sn)"
              v-if="afterSale.afterSaleAllowOperationVO && afterSale.afterSaleAllowOperationVO.cancel" size="small">
        {{ i18nText('common.cancel', '取消售后') }}
      </Button>
    </Card>
    <div class="order-card">
      <h3>{{ afterSale.serviceName }}</h3>
      <p class="global_color fontsize_18">{{ afterSale.orderStatusValue }}</p>
      <p>{{ i18nText('afterSaleOrder.afterSaleOrderID', '售后单号') }}：{{ afterSale.sn }}
        &nbsp;&nbsp;&nbsp;{{ i18nText('order.orderID', '订单号') }}：{{ afterSale.orderSn }}</p>
      <div style="color:#999;" class="operation-time">{{ i18nText('afterSaleOrder.applicationTime', '创建时间') }}：{{ afterSale.createTime }}</div>
      <div class="service-after">
        <div>
          <p>{{ i18nText('afterSaleOrder.returnAddress', '退货地址') }}</p>
          <p>{{ i18nText('address.addressLine1', '详细地址') }}：2992 Fancher Drive</p>
          <p>{{ i18nText('address.cityTown', '城市') }}：Plano &nbsp;&nbsp;&nbsp; {{ i18nText('address.provinceRegionState', '地区') }}：Texas &nbsp;&nbsp;&nbsp;
            {{ i18nText('address.country', '国家') }}：Unit States &nbsp;&nbsp;&nbsp; {{ i18nText('address.postalZIPCode', '邮政编码') }}：75074</p>
        </div>
        <div>
          <img :src="afterSale.goodsImage" alt="" width="60" height="60">
          <span>{{ afterSale.goodsName }}</span>
        </div>
      </div>
    </div>
    <div class="order-card">
      <h3>{{ i18nText('afterSaleOrder.afterSaleStatus', '售后进程') }}</h3>
      <Steps class="progress" :current="logList.length" direction="vertical">
        <Step
          :content="i18nText('common.handler', '操作人') + '：'+ log.operatorName + '   ' + log.createTime"
          :title="log.message"
          v-for="(log, index) in logList"
          :key="index"
        ></Step>
      </Steps>
    </div>
    <div class="order-card">
      <h3 class="mb_10">{{ i18nText('afterSaleOrder.afterSaleOrderInformation', '服务单信息') }}</h3>
      <table border="1" cellpadding='0' cellspacing="0">
        <tr>
          <td>{{ i18nText('order.refundMethod', '退款方式') }}</td>
          <td>{{ afterSale.refundWay === 'ORIGINAL' ? i18nText('order.originalPaymentAccount', '原路退回') : '账号退款' }}</td>
        </tr>
        <tr>
          <td>{{ i18nText('afterSaleOrder.refundAmount', '申请退款金额') }}</td>
          <td>{{ afterSale.applyRefundPrice | unitPrice(i18nText('symbol.currencySymbol', '￥')) }}</td>
        </tr>
        <tr v-if="afterSale.actualRefundPrice">
          <td>{{ i18nText('afterSaleOrder.actualRefundAmount', '实际退款金额') }}</td>
          <td>{{ afterSale.actualRefundPrice | unitPrice(i18nText('symbol.currencySymbol', '￥')) }}</td>
        </tr>
        <template v-if="afterSale.refundWay === 'OFFLINE'">
          <tr>
            <td>退款开户行</td>
            <td>{{ afterSale.bankDepositName }}</td>
          </tr>
          <tr>
            <td>退款开户名</td>
            <td>{{ afterSale.bankAccountName }}</td>
          </tr>
          <tr>
            <td>退款卡号</td>
            <td>{{ afterSale.bankAccountNumber }}</td>
          </tr>
        </template>
        <tr>
          <td>{{ i18nText('afterSaleOrder.applicationType', '商品处理方式') }}</td>
          <td>{{ afterSale.serviceType === 'EXCHANGE_GOODS' ? i18nText('order.exchange', '换货') : i18nText('order.returnAndRefund', '退货退款') }}</td>
        </tr>
        <tr>
          <td>{{ i18nText('afterSaleOrder.returnReason', '退款原因') }}</td>
          <td>{{ afterSale.reasonName }}</td>
        </tr>
        <tr>
          <td>{{ i18nText('order.description', '问题描述') }}</td>
          <td>{{ afterSale.problemDesc }}</td>
        </tr>
      </table>
    </div>
    <div class="order-card" v-if="afterSale.afterSaleImage">
      <h3 class="mb_10">{{ i18nText('common.image', '图片信息') }}</h3>
      <div v-for="img in afterSale.afterSaleImage.split(',')" :key="img">
        <img :src="img" width="200" height="200" @click="perviewImg(img)" class="hover-pointer" alt="">
      </div>
    </div>
    <div class="order-card" v-if="afterSale.afterSaleVideo">
      <h3 class="mb_10">{{ i18nText('common.video', '视频信息') }}</h3>
      <div v-for="url in afterSale.afterSaleVideo.split(',')" :key="url" class="video-download">
        <a href="#" @click="download(url)">{{ getFileName(url) }}({{ i18nText('afterSaleOrder.clickDownloadVideo', '点击下载视频') }})</a>
      </div>
    </div>
    <Modal v-model="logisticsShow" width="530">
      <p slot="header">
        <span>{{ i18nText('afterSaleOrder.returnLogisticsInformation', '提交物流信息') }}</span>
      </p>
      <div>
        <Form ref="form" :model="form" label-position="left" :label-width="150" :rules="rules">
          <FormItem :label="i18nText('afterSaleOrder.carrier', '物流公司')" prop="logisticsId">
            <Select v-model="form.logisticsId" :placeholder="i18nText('afterSaleOrder.pleaseSelectALogisticsCompany', '请选择物流公司')">
              <Option v-for="item in companyList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem :label="i18nText('afterSaleOrder.trackingNumber', '物流单号')" prop="logisticsNo">
            <Input v-model="form.logisticsNo" :placeholder="i18nText('afterSaleOrder.pleaseFillInTheLogisticsTrackingNumber', '请填写物流单号')"></Input>
          </FormItem>
          <FormItem :label="i18nText('afterSaleOrder.shippingTime', '发货时间')" prop="mDeliverTime">
            <DatePicker type="date" style="width:100%" v-model="form.mDeliverTime" @on-change="changeTime"
                        format="yyyy-MM-dd" :placeholder="i18nText('afterSaleOrder.pleaseSelectTheShippingDate', '选择发货时间')"></DatePicker>
          </FormItem>
        </Form>
      </div>
      <div slot="footer" style="text-align: right">
        <Button @click="logisticsShow = false">{{ i18nText('common.close', '关闭') }}</Button>
        <Button type="primary" :loading="submitLoading" @click="submitDelivery">{{ i18nText('common.submit', '提交') }}</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import {afterSaleDetail, afterSaleLog, afterSaleReason, cancelAfterSale} from '@/api/member.js';
import {afterSaleDelivery, getLogisticsCompany} from '@/api/order.js';
import {afterSaleStatusList} from '../enumeration.js'
import {isEmpty} from "@/utils/util";
import { i18nText } from '@/utils/i18n'

export default {
  name: 'aftersale-detail',
  data() {
    return {
      afterSale: {}, // 售后详情数据
      logList: [], // 日志
      reasonList: [], // 售后原因列表
      afterSaleStatusList, // 售后状态列表
      companyList: [], // 物流公司列表
      logisticsShow: false, // 物流信息modal
      form: { // 物流信息数据
        afterSaleSn: '',
        logisticsId: '',
        logisticsNo: '',
        mDeliverTime: ''
      },
      rules: { // 必填校验
        logisticsId: [{required: true, message: i18nText('afterSaleOrder.pleaseSelectALogisticsCompany', '请选择物流公司')}],
        logisticsNo: [{required: true, message: i18nText('afterSaleOrder.pleaseFillInTheLogisticsTrackingNumber', '请填写物流单号')}],
        mDeliverTime: [{required: true, message: i18nText('afterSaleOrder.pleaseSelectTheShippingDate', '请选择发货时间')}]
      },
      submitLoading: false // 提交加载状态
    };
  },
  methods: {
    getDetail() { // 售后详情
      afterSaleDetail(this.$route.query.sn).then(res => {
        if (res.success) {
          this.afterSale = res.result;
          this.afterSale.serviceName = this.filterOrderStatus(this.afterSale.serviceStatus)
          // 如果是原因id，则调接口查询原因中文释义
          const pattern3 = new RegExp('[0-9]+');
          if (pattern3.test(this.afterSale.reason)) {
            this.getReason(this.afterSale.serviceType)
          } else {
            this.$set(this.afterSale, 'reasonName', this.afterSale.reason)
          }
        }
      })
    },
    getReason(type) { // 获取售后原因
      afterSaleReason(type).then(res => {
        if (res.success) {
          this.reasonList = res.result
          this.reasonList.forEach(e => {
            if (e.id === this.afterSale.reason) {
              this.$set(this.afterSale, 'reasonName', e.reason)
            }
          })
        }
      })
    },
    getLog() { // 获取售后日志
      afterSaleLog(this.$route.query.sn).then(res => {
        this.logList = res.result;
      })
    },
    filterOrderStatus(status) { // 获取订单状态中文
      const ob = this.afterSaleStatusList.filter(e => {
        return e.status === status
      });
      if (ob.length) return ob[0].name
    },
    perviewImg(img) { // 查看图片
      window.open(img, '_blank')
    },
    cancel(sn) { // 取消售后申请
      this.$Modal.confirm({
        title: i18nText('common.cancel', '取消'),
        content: '<p>' + i18nText('afterSaleOrder.sureCancelAfterSalesApplication', '确定取消此次售后申请吗？') + '</p>',
        onOk: () => {
          cancelAfterSale(sn).then(res => {
            if (res.success) {
              this.$Message.success(i18nText('afterSaleOrder.successfullyCanceledAfterSalesApplication', '取消售后申请成功'))
              this.getDetail()
            }
          })
        },
        onCancel: () => {
        }
      });
    },
    // 获取物流公司列表
    getCompany() {
      getLogisticsCompany().then(res => {
        if (res.success) {
          this.companyList = res.result
        }
      })
    },
    // 提交物流信息
    submitDelivery() {
      this.submitLoading = true
      afterSaleDelivery(this.form).then(res => {
        if (res.success) {
          this.logisticsShow = false;
          this.$Message.success(i18nText('common.submittedSuccessfully', '提交成功'))
          this.getDetail()
        }
        this.submitLoading = false
      }).catch(() => {
        this.submitLoading = false
      })
    },
    // 提交物流modal
    openModal() {
      this.form.afterSaleSn = this.afterSale.sn
      this.logisticsShow = true;
      this.$refs.form.resetFields()
      if (!this.companyList.length) {
        this.getCompany()
      }
    },
    // 格式化时间
    changeTime(time) {
      this.form.mDeliverTime = time;
    },
    /**
     * 判断是否为图片
     */
    judgeImage(image) {
      // 先获取链接后缀
      const suffix = image.substring(image.lastIndexOf("."))
      const imageSuffix = ['.xbm', '.tif', '.pjp', '.svgz', '.jpg', '.jpeg', '.ico', '.tiff', '.gif', '.svg', '.jfif', '.webp', '.png', '.bmp', '.pjpeg', '.avif']
      const result = imageSuffix.filter(item => item === suffix)
      if (isEmpty(result)) {
        return false
      }
      return true
    },
    /**
     * 获取文件名称
     */
    getFileName(url) {
      return url.substring(url.lastIndexOf("/") + 1)
    },
    /**
     * 视频下载
     */
    download(url) {
      fetch(url)
        .then(res => res.blob())
        .then(blob => {
          const a = document.createElement("a")
          const objectUrl = window.URL.createObjectURL(blob)
          a.download = this.getFileName(url)
          a.href = objectUrl
          a.click()
          window.URL.revokeObjectURL(objectUrl)
          a.remove()
        })
    }
  },
  mounted() {
    this.getDetail();
    this.getLog()
  }
};
</script>
<style lang="scss" scoped>
.order-card {
  padding: 10px;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #e8eaec;
  position: relative;

  .global_color {
    color: $theme_color;
  }

  p {
    color: #999;
    margin: 3px;
  }

  h3 {
    font-weight: normal;
    font-size: 16px;
  }

  .operation-time {
    position: absolute;
    right: 20px;
    top: 10px;
  }

  &:last-child {
    border: none;
  }
}

.service-after {
  border: 1px solid #eee;
  //display: flex;
  height: 160px;
  padding: 10px;

  > div:nth-child(1) {
    width: 100%;
    font-size: 12px;
    font-weight: bold;
    //text-align: center;
    //line-height: 60px;
    span {
      color: $theme_color;
    }

    //border-right: 1px solid #eee;
    border-bottom: 1px solid #eee;
  }

  > div:nth-child(2) {
    //padding-left: 15px;
    img {
      vertical-align: top;
    }

    span {
      color: #999;
    }
  }
}

/** 售后进度条 */
.progress {
  margin: 15px 0;
}

table {
  border-color: #eee;
  width: 100%;
  color: #999;

  tr {
    td:nth-child(1) {
      width: 200px;
    }
  }

  td {
    padding: 5px;
  }
}

.video-download {
  margin-bottom: 5px;
}
</style>
